//using DBLibrary.DataBase;
using DevExpress.Data.XtraReports.Native;
using DevExpress.Mvvm;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Core.ConditionalFormatting;
using DevExpress.Xpo;
using DevExpress.XtraPrinting.Native;
using DevExpress.XtraRichEdit.API.Native;
using DXApplications.Models;
using DXApplications.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using System.Windows.Interop;

namespace DXApplications.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly ApiService _apiService;
        public ObservableRangeCollection<TypesModel> FileTypes { get; set; }= new ObservableRangeCollection<TypesModel>();
        public ObservableRangeCollection<TimeStampModel> CurrentFileTime { get; set; } = new ObservableRangeCollection<TimeStampModel>();

        public MainViewModel()
        {
            _apiService = new ApiService();
            InitializeAsync();
        }

        private async void InitializeAsync()
        {
            await InitializeFileTypesAsync();
            await UpdateViewAsync();
        }
        // 初始化文件类型列表（异步版本）
        private async Task InitializeFileTypesAsync()
        {
            try
            {
                string logFilePath = "d:\\temp\\app_log.txt";
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(logFilePath));
                System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 开始初始化文件类型列表\r\n");
                
                FileTypes.Clear();
                
                // 通过API服务获取文件类型
                var fileTypes = await _apiService.GetFileTypesAsync();
                
                if (fileTypes != null)
                {
                    System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 成功获取到文件类型数量: {fileTypes.Count}\r\n");
                    
                    // 打印每个文件类型的详细信息
                    for (int i = 0; i < fileTypes.Count; i++)
                    {
                        var type = fileTypes[i];
                        System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 文件类型 {i+1}: FileTypeID={type.FileTypeID}, FileTypeName={type.FileTypeName}, MemoryStrength={type.MemoryStrength}\r\n");
                    }
                    
                    FileTypes.AddRange(fileTypes);
                    System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 成功添加到FileTypes集合，当前集合数量: {FileTypes.Count}\r\n");
                }
                else
                {
                    System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 获取到的文件类型列表为空\r\n");
                }
            }
            catch (Exception ex)
            {
                string logFilePath = "d:\\temp\\app_log.txt";
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(logFilePath));
                System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 获取文件类型时发生异常: {ex.Message}\r\n");
                System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 内部异常: {ex.InnerException?.Message}\r\n");
                System.IO.File.AppendAllText(logFilePath, $"[{DateTime.Now}] 堆栈跟踪: {ex.StackTrace}\r\n");
                
                // 显示错误消息
                this.GetService<DXMessageBoxService>()?.ShowMessage(
                    $"获取文件类型失败: {ex.Message}",
                    "错误",
                    MessageButton.OK,
                    MessageIcon.Error);
            }
        }

        // 更新视图数据（异步版本）
        public async Task UpdateViewAsync()
        {
            try
            {
                CurrentFileTime.Clear();
                // 通过API服务获取文件列表
                var files = await _apiService.GetFilesAsync();
                
                if (files != null)
                {
                    foreach (var file in files)
                {
                    // 获取复习信息
                    var reviewInfo = await _apiService.GetReviewInfoAsync(file.FileID);
                    if (reviewInfo != null)
                    {
                        file.NextTime = reviewInfo.NextReviewTime;
                    }
                    else
                    {
                        // 如果获取复习信息失败，使用本地计算
                        var memoryCount = 0; // 这里可以尝试从本地获取或设置默认值
                        var memoryStrength = 1.0; // 默认记忆强度
                        file.NextTime = CalculateNextReviewTime(file.Time, memoryCount, memoryStrength, 1.5, 0.9);
                    }
                    
                        CurrentFileTime.Add(file);
                    }
                }
            }
            catch (Exception ex)
            {
                // 显示错误消息
                this.GetService<DXMessageBoxService>()?.ShowMessage(
                    $"更新数据失败: {ex.Message}",
                    "错误",
                    MessageButton.OK,
                    MessageIcon.Error);
            }
        }
        // 添加文件（异步版本）
        public async Task AddFileAsync(TimeStampModel fileInfo)
        {
            try
            {
                // 通过API服务添加文件
                var success = await _apiService.AddFileAsync(fileInfo);
                
                if (success)
                {
                    // 重新加载数据
                    await UpdateViewAsync();
                    
                    // 计算下一次复习时间
                    var fileType = FileTypes.FirstOrDefault(t => t.FileTypeID == fileInfo.TypeID);
                    if (fileType != null)
                    {
                        fileInfo.NextTime = CalculateNextReviewTime(DateTime.Now, 1, fileType.MemoryStrength, 1.5, 0.9);
                    }
                }
                else
                {
                    // 显示错误消息
                    this.GetService<DXMessageBoxService>()?.ShowMessage(
                        "添加文件失败",
                        "错误",
                        MessageButton.OK,
                        MessageIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // 显示错误消息
                this.GetService<DXMessageBoxService>()?.ShowMessage(
                    $"添加文件发生错误: {ex.Message}",
                    "错误",
                    MessageButton.OK,
                    MessageIcon.Error);
            }
        }
        // 添加时间戳（异步版本）
        public async Task AddTimeStampAsync(TimeStampModel timeStampModel)
        {
            try
            {
                // 通过API服务添加时间戳
                var success = await _apiService.AddTimestampAsync(timeStampModel);
                
                if (success)
                {
                    // 重新加载数据
                    await UpdateViewAsync();
                }
                else
                {
                    // 显示错误消息
                    this.GetService<DXMessageBoxService>()?.ShowMessage(
                        "添加时间戳失败",
                        "错误",
                        MessageButton.OK,
                        MessageIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // 显示错误消息
                this.GetService<DXMessageBoxService>()?.ShowMessage(
                    $"添加时间戳发生错误: {ex.Message}",
                    "错误",
                    MessageButton.OK,
                    MessageIcon.Error);
            }
        }
      

        public void OpenFile(string filePath)
        {
            try
            {
                // 执行打开操作
                // 使用ProcessStartInfo类创建进程启动信息
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = filePath,  // 直接使用文件路径
                    UseShellExecute = true  // 必须设置为true才能调用系统默认程序
                };
                // 启动进程
                Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                MessageBoxServiceExtensions.ShowMessage(
                    this.GetService<DXMessageBoxService>(),
                    $"打开文件发生报错: {ex.Message}",
                    "错误",
                    MessageButton.OK,
                    MessageIcon.Error);
               

            }
           
        }

        /// <summary>
        /// 计算目标保留率对应的复习间隔（小时）
        /// </summary>
        /// <param name="targetRetention">目标保留率（0~1，如0.7表示70%）</param>
        /// <param name="memoryStrength">当前记忆强度S</param>
        /// <returns>间隔时间（小时）</returns>
        private double CalculateReviewInterval(double targetRetention, double memoryStrength)
        {
            if (targetRetention <= 0 || targetRetention >= 1)
                throw new ArgumentException("目标保留率必须在(0,1)之间", nameof(targetRetention));
            if (memoryStrength <= 0)
                throw new ArgumentException("记忆强度必须大于0", nameof(memoryStrength));

            // 公式：t = S * ln(1/R)
            return memoryStrength * Math.Log(1 / targetRetention);
        }

        /// <summary>
        /// 根据复习次数计算当前记忆强度
        /// </summary>
        /// <param name="reviewCount">复习次数（从1开始）</param>
        /// <returns>当前记忆强度S</returns>
        private double GetMemoryStrength(int reviewCount,double MemoryStrength, double reinforcementFactor = 1.5)
        {
           
            if (reviewCount < 1)
                throw new ArgumentException("复习次数不能小于1", nameof(reviewCount));

            // 公式：S(n) = S0 * k^(n-1)
            return MemoryStrength * Math.Pow(reinforcementFactor, reviewCount - 1);
        }

        /// <summary>
        /// 计算下次复习时间
        /// </summary>
        /// <param name="lastReviewTime">最近一次复习时间</param>
        /// <param name="reviewCount">当前是第几次复习（从1开始）</param>
        /// <param name="targetRetention">目标保留率（默认0.7，即70%）</param>
        /// <returns>下次复习时间</returns>
        public DateTime CalculateNextReviewTime(
            DateTime lastReviewTime,
            int reviewCount, 
            double MemoryStrength,
            double reinforcementFactor = 1.5,
            double targetRetention = 0.7)
        {
            // 1. 获取当前记忆强度（随复习次数增强）
            double currentMemoryStrength = GetMemoryStrength(reviewCount, MemoryStrength, reinforcementFactor);
            //7 36 410.625
            //6 24 182.5
            // 2. 计算间隔时间（小时）
            double intervalHours = CalculateReviewInterval(targetRetention, currentMemoryStrength);
            //24 19.2
            // 3. 计算下次复习时间
            return lastReviewTime.AddHours(intervalHours);
        }

        public async Task UpdateTypesAsync()
        {
            try
            {
                // 通过API服务获取文件类型
                var fileTypes = await _apiService.GetFileTypesAsync();
                if (fileTypes != null)
                {
                    FileTypes.Clear();
                    FileTypes.AddRange(fileTypes);
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                DXMessageBox.Show("更新文件类型失败: " + ex.Message, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        internal async Task DeleteFileAsync(TimeStampModel timeStampModel)
        {
            try
            {
                // 通过API服务删除文件
                bool success = await _apiService.DeleteFileAsync(timeStampModel.FileID);
                if (!success)
                {
                    DXMessageBox.Show("删除文件失败", "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
                else
                {
                    // 删除成功后从当前视图中移除相关项
                    var itemToRemove = CurrentFileTime.FirstOrDefault(item => item.FileID == timeStampModel.FileID);
                    if (itemToRemove != null)
                    {
                        CurrentFileTime.Remove(itemToRemove);
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                DXMessageBox.Show("删除文件时发生错误: " + ex.Message, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }
    }
   
}
